// function getOltNeedExpandListByCity(city_name) {
//     var infoCenter = document.getElementById('info_body');
//     var infoCenterHtml = '<ul class="list-group" style="width: 100%">';
//     $.ajax({
//         url: '/getOltNeedExpandListByCity?city_name=' + city_name,
//         dataType: 'JSON',
//         async: false,
//         success: function (data) {
//             for (var i in data) {
//                 var maxFlow = data[i]['maxFlow'];
//                 var cityName = data[i]['city_name'];
//                 var oltIP = data[i]['ip'];
//                 var actUsers = data[i]['act_users'];
//                 var devName = data[i]['olt_name'];
//                 var upSpeed = data[i]['upspeed'];
//                 if (maxFlow <= 0.7) {
//                     var info = '<li class="list-group-item" id="' + oltIP + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '-' + devName + '(' + oltIP + ')--上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '--活跃用户数:' + actUsers + '</li>'
//
//                 } else if (maxFlow > 0.7 && maxFlow <= 0.8) {
//                     var info = '<li class="list-group-item list-group-item-info" id="' + oltIP + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '-' + devName + '(' + oltIP + ')--上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '--活跃用户数:' + actUsers + '</li>'
//
//                 } else if (maxFlow > 0.8 && maxFlow <= 0.9) {
//                     var info = '<li class="list-group-item list-group-item-warning" id="' + oltIP + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '-' + devName + '(' + oltIP + ')--上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '--活跃用户数:' + actUsers + '</li>'
//
//                 } else if (maxFlow > 0.9) {
//                     var info = '<li class="list-group-item list-group-item-danger" id="' + oltIP + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '-' + devName + '(' + oltIP + ')--上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '--活跃用户数:' + actUsers + '</li>'
//
//                 }
//                 infoCenterHtml += info + '  ';
//             }
//
//         }
//     });
//     infoCenter.innerHTML = infoCenterHtml + '</ul>'
// }

// function getSWNeedExpandListByCity(city_name) {
//     var infoCenter = document.getElementById('info_body');
//     var infoCenterHtml = '<ul class="list-group" style="width: 100%">';
//     $.ajax({
//         url: '/getSWNeedExpandListByCity?city_name=' + city_name,
//         dataType: 'JSON',
//         async: false,
//         success: function (data) {
//             for (var i in data) {
//                 var maxFlow = data[i]['utilization'];
//                 var cityName = data[i]['city'];
//                 var devName = data[i]['circuit_name'];
//                 var upSpeed = data[i]['bandwith'];
//                 var aDevice = data[i]['A_device'];
//                 switch (maxFlow) {
//                     case maxFlow <= 0.7:
//
//                 }
//                 if (maxFlow <= 0.7) {
//                     var info = '<li class="list-group-item" id="li_' + aDevice + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '    ' + devName + '    上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '</li>'
//
//                 } else if (maxFlow > 0.7 && maxFlow <= 0.8) {
//                     var info = '<li class="list-group-item list-group-item-info" id="li_' + aDevice + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '    ' + devName + '    上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '</li>'
//
//                 } else if (maxFlow > 0.8 && maxFlow <= 0.9) {
//                     var info = '<li class="list-group-item list-group-item-warning" id="li_' + aDevice + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '    ' + devName + '    上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '</li>'
//
//                 } else if (maxFlow > 0.9) {
//                     var info = '<li class="list-group-item list-group-item-danger" id="li_' + aDevice + '" ondblclick="showTopo(this.id)">' +
//                         cityName + '    ' + devName + '    上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '</li>'
//
//
//                 }
//
//                 infoCenterHtml += info + '  ';
//             }
//
//         }
//     });
//     infoCenter.innerHTML = infoCenterHtml + '</ul>'
// }


function showSWTopo(sw_name) {
    swName = sw_name
    $('#modal_topo_body')[0].innerHTML = '<canvas id="topo_canvas" style="height: 100%;width: 100%;background-color: #0F161C"></canvas>'
    DrawSWTopo(swName);
    $('#modal_topo').modal('show');
    $('#topo_title')[0].innerText = sw_name+'拓扑图'
}

function showOLTTopo(olt_name) {
    oltName = olt_name;
    var swName = '';
    $.ajax({
        url: '/getSWNameByOltName?olt_name='+olt_name,
        dataType: 'JSON',
        async: false,
        success: function (data) {
            swName = data['sw_name'];
        }
    });
    $('#modal_topo_body')[0].innerHTML = '<canvas id="topo_canvas" style="height: 100%;width: 100%;background-color: #0F161C"></canvas>'
    DrawSWTopo(swName);
    $('#modal_topo').modal('show');
    $('#topo_title')[0].innerText = olt_name+'拓扑图'
}

function showOltPonUserChart(olt_name) {
    oltName = olt_name;
    $('#modal_topo_body')[0].innerHTML = '<canvas id="chart_canvas" style="height: 100%;width: 100%;background-color: #0F161C"></canvas>'
    // DrawSWTopo(swName);
    $('#modal_topo').modal('show');
    $('#topo_title')[0].innerText = olt_name+'已接用户';
    createPonUserChart(oltName);
    myChartPonUser = echarts.init(document.getElementById('chart_canvas'));
    myChartPonUser.setOption(optionPonUser);
    $('#chart_canvas').css('height','700px')
    $('#chart_canvas').css('width','1000px')
    myChartPonUser.resize();

}


function createPonUserChart(oltName){
    // var ponUserData = Array();
    // ponUserData = getPonUserList(oltName);
    var ponUserData = eval("("+getPonUserList(oltName)+")");
    optionPonUser = {
        title: {
            text: '端口用户数分布表',
            textStyle: {
                fontSize: 36,
                align: 'center',
                color:'#FFFFFF'
            },
        },
        series: {
            type: 'sunburst',
            highlightPolicy: 'ancestor',
            data: ponUserData,
            radius: [0, '95%'],
            sort: null,
            levels: [{}, {
                r0: '15%',
                r: '40%',
                itemStyle: {
                    borderWidth: 2
                },
                label: {
                    rotate: 'tangential',
                    color: '#000000',
                    fontSize:15
                }
            }, {
                r0: '40%',
                r: '80%',
                label: {
                    align: 'right',
                    color: '#000000',
                    fontSize:15

                }
            }, {
                r0: '80%',
                r: '85%',
                label: {
                    position: 'outside',
                    padding: 3,
                    silent: false,
                    fontSize:20
                },
                itemStyle: {
                    borderWidth: 3
                }
            }]
        }
    };

}


$('#modal_topo').on('hide.bs.modal',function () {
    // topoCan = document.getElementById('topo_canvas')
    // topoCan.width = topoCan.width;
    $('#modal_topo_body')[0].innerHTML = ''
    // stage.clear();
    // scene.clear();
    // scene = null;
    // stage = null;
});

function setColor(val, valList) {
    var valListTmp = valList.sort(intCompare);
    var param = val / valListTmp[valListTmp.length - 1] * 50

    r = 255;
    g = 200 - param * 4;
    b = 0;
    return 'rgb(' + r + ',' + g + ',' + b + ')'
}

function setMapColor(val, valList) {
    var valListTmp = valList.sort(intCompare);
    var param = val / valListTmp[valListTmp.length - 1] * 50

    r = param * 4;
    g = 255;
    b = 0;
    return 'rgb(' + r + ',' + g + ',' + b + ')'
}

function gradientColor(startColor, endColor, step) {
    startRGB = this.colorRgb(startColor);//转换为rgb数组模式
    startR = startRGB[0];
    startG = startRGB[1];
    startB = startRGB[2];
    endRGB = this.colorRgb(endColor);
    endR = endRGB[0];
    endG = endRGB[1];
    endB = endRGB[2];
    sR = (endR - startR) / step;//总差值
    sG = (endG - startG) / step;
    sB = (endB - startB) / step;
    var colorArr = [];
    for (var i = 0; i < step; i++) {
        //计算每一步的hex值
        var hex = this.colorHex('rgb(' + parseInt((sR * i + startR)) + ',' + parseInt((sG * i + startG)) + ',' + parseInt((sB * i + startB)) + ')');
        colorArr.push(hex);
    }
    return colorArr;
}

// 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
gradientColor.prototype.colorRgb = function (sColor) {
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    var sColor = sColor.toLowerCase();
    if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
            var sColorNew = "#";
            for (var i = 1; i < 4; i += 1) {
                sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
            }
            sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for (var i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
        }
        return sColorChange;
    } else {
        return sColor;
    }
};

// 将rgb表示方式转换为hex表示方式
gradientColor.prototype.colorHex = function (rgb) {
    var _this = rgb;
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    if (/^(rgb|RGB)/.test(_this)) {
        var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
        var strHex = "#";
        for (var i = 0; i < aColor.length; i++) {
            var hex = Number(aColor[i]).toString(16);
            hex = hex < 10 ? 0 + '' + hex : hex;// 保证每个rgb的值为2位
            if (hex === "0") {
                hex += hex;
            }
            strHex += hex;
        }
        if (strHex.length !== 7) {
            strHex = _this;
        }
        return strHex;
    } else if (reg.test(_this)) {
        var aNum = _this.replace(/#/, "").split("");
        if (aNum.length === 6) {
            return _this;
        } else if (aNum.length === 3) {
            var numHex = "#";
            for (var i = 0; i < aNum.length; i += 1) {
                numHex += (aNum[i] + aNum[i]);
            }
            return numHex;
        }
    } else {
        return _this;
    }
}


function getHeight(val, valList) {
    var valListTmp = valList.sort(intCompare);
    var param = val / valListTmp[valListTmp.length - 1] * 150
    return param;
}

function intCompare(x, y) {
    if (x < y) {
        return -1;
    } else if (x > y) {
        return 1;
    } else {
        return 0;
    }
}


function renderEachCity() {
    var option = {
        xAxis: [],
        yAxis: [],
        grid: [],
        series: []
    };


    echarts.util.each(rawData, function (dataItem, idx) {
        var geoCoord = geoCoordMap[dataItem[0] + '市'];
        var coord = myChart.convertToPixel('geo', geoCoord);

        idx += '';

        inflationData = [dataItem[1], dataItem[2]];


        option.xAxis.push({
            id: idx,
            gridId: idx,
            type: 'category',
            name: dataItem[0],
            nameLocation: 'middle',
            nameGap: 3,
            nameTextStyle:{
                fontSize:15,
                color: '#FFFFFF'
            },
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                show: false
            },
            axisLine: {
                onZero: false,
                lineStyle: {
                    color: '#000000'
                }
            },
            data: ['待扩容OLT', '待扩容SW'],
            // data: mapTip,
            z: 100

        });
        option.yAxis.push({
            id: idx,
            gridId: idx,
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                show: false
            },
            axisLine: {
                show: false,
                lineStyle: {
                    color: '#1C70B6'
                }
            },
            z: 100
        });

        option.grid.push({
            id: idx,
            width: 50,
            height: getHeight(dataItem[2], valList),
            left: coord[0] - 25,
            top: coord[1] - getHeight(dataItem[1], valList) / 2,
            z: 100
        });
        option.series.push({
            id: idx,
            type: 'bar',
            xAxisId: idx,
            yAxisId: idx,
            barGap: 0,
            barCategoryGap: 0,
            // data: inflationData,
            data: inflationData,
            z: 100,
            itemStyle: {
                normal: {
                    color: function (params) {
                        // 柱状图每根柱子颜色
                        var colorList = ['#5ECF35', '#00BCD2'];
                        return colorList[params.dataIndex];

                        // return setColor(dataItem[1], valList);
                        // color: colorListBar[dataItem[1]]

                    }
                }
            }
        });
    });
    myChart.setOption(option);
}

setTimeout(renderEachCity, 0);

function showDateTime() {
    var myDate = new Date(); //获取当天日期
    var sYear = myDate.getFullYear(); //获取年
    var sMonth = formatTwoDigits(myDate.getMonth() + 1); //获取月
    var sDate = formatTwoDigits(myDate.getDate()); //获取日
    var h = myDate.getHours(); //获取小时
    var m = myDate.getMinutes(); //获取分钟
    var s = myDate.getSeconds(); //获取秒
    //输入日期和星期
    h = formatTwoDigits(h);  //格式化小时,如果不足两位在前面补0
    m = formatTwoDigits(m); //格式化分钟,如果不足两位在前面补0
    s = formatTwoDigits(s); //格式化秒钟后,如果不足两位在前面补0
    //显示时间
    document.getElementById("clock").innerHTML = (sYear + "-" + sMonth + "-" + sDate + " " + h + ":" + m + ":" + s + "    ");
    setTimeout("showDateTime()", 1000);//每秒执行一次showDateTime函数
}

window.onload = showDateTime;//在整个页面加载完成后执行此函数
//如果输入数是一位数,则在十位上补0
function formatTwoDigits(s) {
    if (s < 10)
        return "0" + s;
    else
        return s;
}


function showTopDivCityInfo() {
    // $('#top_div_city').slideToggle(800,);
    // setTimeout('cityOltChart.setOption(optionCityOlt)',1050);
    // setTimeout('cityOltChart.resize()',1100);
    cityOltChart.setOption(optionCityOlt);
    cityOltChart.resize();
}

function showTopDivSW() {
    $('#top_div_sw').slideToggle(800);
}

function showTopDivOLT() {
    $('#top_div_olt').slideToggle(800);
}

function hideTopDivCity() {
    cityBoundChart.clear();
    $('#city_name')[0].innerText = '';
    $('#all_user_span')[0].innerText = '';
    $('#all_act_user_span')[0].innerText = '';
    $('#all_itv_span')[0].innerText = '';
    $('#all_sw_span')[0].innerText = '';
    $('#all_olt_span')[0].innerText = '';

    cans = document.getElementsByClassName('barCanvas');
    for (can in cans) {
        cans[can].width = cans[can].width;
    }
    $('#city_detail_list')[0].innerHTML = '';
    // $("#city_detail_list")[0].innerHTML='';
    $('#top_div_city').slideToggle(800);

}


function hideTopDiv(id) {
    // console.log($('#city_olt_chart_div'))
    if ($('#city_olt_chart_div')[0].innerHTML != '') {
        cityOltChart.clear();
    }
    $('#' + id).slideToggle(800);
}

function formatInt(num) {
    var reg = /\d{1,3}(?=(\d{3})+$)/g;
    return (num + '').replace(reg, '$&,');
}


function drawBarSW(num, id) {
    var canSW = document.getElementById(id);
    var ctx = canSW.getContext("2d");
    canWidth = canSW.width;
    canHeight = canSW.height;
    $('#' + id + '_num')[0].innerText = num;
    var b = parseInt(num / 100);
    var s = parseInt((num - b * 100) / 10);
    var g = num % 10;
    ctx.fillStyle = "#EA4D58";
    for (var i = 0; i < b; i++) {
        canHeight = canHeight - 11;
        ctx.fillRect(0, canHeight, canSW.width, 10);
    }
    ctx.fillStyle = "#F1E723";
    for (var i = 0; i < s; i++) {
        canHeight = canHeight - 6;
        ctx.fillRect(0, canHeight, canSW.width, 5);
    }
    ctx.fillStyle = "#90E67E";
    if (g > 0) {
        for (var i = 0; i < g; i++) {
            canHeight = canHeight - 3;
            ctx.fillRect(0, canHeight, canSW.width, 2);
        }
    }
}



function drawBarOLT(num, id) {
    var canOLT = document.getElementById(id);
    var ctx = canOLT.getContext("2d");
    canWidth = canOLT.width;
    canHeight = canOLT.height;
    $('#' + id + '_num')[0].innerText = num;
    var b = parseInt(num / 100);
    var s = parseInt((num - b * 100) / 10);
    var g = num % 10;
    ctx.fillStyle = "#EA4D58";
    for (var i = 0; i < b; i++) {
        canHeight = canHeight - 11;
        ctx.fillRect(0, canHeight, canOLT.width, 10);
    }
    ctx.fillStyle = "#F1E723";
    for (var i = 0; i < s; i++) {
        canHeight = canHeight - 6;
        ctx.fillRect(0, canHeight, canOLT.width, 5);
    }
    ctx.fillStyle = "#90E67E";
    if (g > 0) {
        for (var i = 0; i < g; i++) {
            canHeight = canHeight - 3;
            ctx.fillRect(0, canHeight, canOLT.width, 2);
        }
    }
}


function showCityDetail(id) {
    var infoCenter = document.getElementById('city_detail_list');
    $('#city_detail_list')[0].innerHTML = '';

    var idList = Array();
    var city_name = $('#city_name')[0].innerText + '市'
    idList = id.split('_');
    if (idList[0] == 'sw') {
        $.ajax({
            url: '/getSWListByCityNameAndUtilization?city_name=' + city_name + '&option=' + idList[1],
            dataType: 'JSON',
            // async: false,
            beforeSend: function () {
                ShowLoading();
            },
            complete: function () {
                HiddenLoading();
            },
            success: function (data) {
                console.log(data)
                for (i = 0; i < data.length; i++) {
                    var maxFlow = data[i]['max_utilization'];
                    var cityName = data[i]['city'];
                    var swIP = data[i]['Loopback_sw'];
                    var devName = data[i]['sw_name'];
                    var info = '<li class="list-group-item" style="color: #ffffff;font-size: 20px"  >' +
                        cityName + '    ' + devName + '    设备IP:' + swIP + '--带宽利用率:' + maxFlow +
                        '<button class="close" id="' + devName + '" onclick="showSWTopo(\'' + devName + '\')">' +
                        '<span class="glyphicon glyphicon-zoom-in" aria-hidden="true"></span></button></li>'
                    infoCenter.innerHTML += info
                }
            }
        })
    } else if (idList[0] == 'olt') {
        $.ajax({
            url: '/getOLTListByCityNameAndUtilization?city_name=' + city_name + '&option=' + idList[1],
            dataType: 'JSON',
            // async: false,
            beforeSend: function () {
                ShowLoading();
            },
            complete: function () {
                HiddenLoading();
            },
            success: function (data) {
                for (i = 0; i < data.length; i++) {
                    var maxFlow = data[i]['max_flow'];
                    var cityName = data[i]['city_name'];
                    var oltIP = data[i]['olt_ip'];
                    var actUsers = data[i]['act_users'];
                    var devName = data[i]['olt_name'];
                    var upSpeed = data[i]['upspeed'];
                    var info = '<li class="list-group-item" style="color: #ffffff;font-size: 20px" id="' + devName + '" >' +
                        cityName + '-' + devName + '(' + oltIP + ')--上联总带宽:' + upSpeed + 'Gb--带宽利用率:' + maxFlow + '--活跃用户数:' + actUsers
                        + '<button class="close" id="' + devName + '" onclick="showOLTTopo(\'' + devName + '\')">'
                        +'<span class="glyphicon glyphicon-zoom-in" aria-hidden="true"></span></button>'
                        +'<button class="close" id="' + devName + '" onclick="showOltPonUserChart(\'' + devName + '\')">'
                        +'<span class="glyphicon glyphicon-user" aria-hidden="true"></span></button>' +
                        '</li>';
                    infoCenter.innerHTML += info
                }
            }
        })

    }

}









//显示加载数据
function ShowLoading() {
    $("#loading").show();
}

//隐藏加载数据
function HiddenLoading() {
    $("#loading").hide();
}




